package com.hitqz.robot.camera.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.hitqz.robot.api.business.enums.FormConfigEnum;
import com.hitqz.robot.api.business.enums.RobotParamsFormFieldEnum;
import com.hitqz.robot.api.business.event.FormUpdateEvent;
import com.hitqz.robot.api.common.dto.form.FormFieldConfigUpdateDto;
import com.hitqz.robot.camera.communication.NetworkServiceThreadPool;
import com.hitqz.robot.camera.entity.ConstantsFace;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@AllArgsConstructor
@Slf4j
public class HkParamsListener {

    @EventListener
    public void onParamsUpdate(FormUpdateEvent event) {
        NetworkServiceThreadPool.dealEvent(() -> {
            String formName = event.getFormName();
            if (!Objects.equals(formName, FormConfigEnum.ROBOT_PARAMS_CONFIG.getFormName())) {
                return;
            }
            List<FormFieldConfigUpdateDto> fields = event.getUpdateFields();
            List<FormFieldConfigUpdateDto> hkFields = fields.stream().filter(f -> f.getFieldName().toUpperCase().contains("HK")).toList();
            try {
                this.updateParams(hkFields);
            }catch (Exception e){
                log.info("[HK]更新配置参数失败",e);
            }
            log.info("[HK]更新配置参数成功");
        });
    }


    private void updateParams(List<FormFieldConfigUpdateDto> fields) throws InterruptedException {
        if (fields.isEmpty()) {
            return;
        }
        for (FormFieldConfigUpdateDto field : CollUtil.emptyIfNull(fields)) {
            try {
                String name = field.getFieldName();
                RobotParamsFormFieldEnum fieldEnum = RobotParamsFormFieldEnum.fromFieldName(name);
                if (fieldEnum == null) {
                    continue;
                }
                switch (fieldEnum) {
                    case HK_VOICE_PLAY_ENABLE:
                        ConstantsFace.voicePlayEnable = Objects.equals(field.getCurrentValue(),"1");
                        break;
                    case HK_VOICE_PLAY_IP:
                        ConstantsFace.voicePlayIp = field.getCurrentValue();
                        break;
                }
            } catch (Exception e) {
                log.error("[track]机器人参数更新异常", e);
            }
        }


    }

}
    
